#include "NetIO.h"

Acceptor::Acceptor( Reactor *reactor )
	: port_( 0 )
	, reactor_( reactor )
{

}

Acceptor::Acceptor( short port, const string &ip, Reactor *reactor )
	: ip_( ip )
	, port_( port )
	, reactor_( reactor )
{
	open( port_, ip_ );
}

Acceptor::~Acceptor( void )
{
	closesocket( handle_ );
}

int Acceptor::open( short port, const string &ip )
{
	if( is_open( ) )
		return -1;

	port_ = port;
	ip_ = ip;
	handle_.open( );

	sockaddr_in addr = {0};
	addr.sin_family = AF_INET;
	addr.sin_port = htons( port_ );
	if( ip.size( ) == 0 )
		addr.sin_addr.s_addr = INADDR_ANY;
	else
		addr.sin_addr.s_addr = inet_addr( ip.c_str( ) );

	bind( handle_, ( sockaddr* ) &addr, sizeof( addr ) );
	listen( handle_, 5 );
	SockOps::set_non_blocking( handle_ );

	reactor_->register_handler( handle_ );
	return 0;
}

int Acceptor::async_accept( void *act )
{
	return reactor_->async_accept( handle_, act );
}

void Acceptor::close( )
{
	reactor_->cancel_handle( handle_ );
	handle_.close( );
}

bool Acceptor::is_open( )
{
	return handle_.is_open( );
}
